import styled from "styled-components";
import {memo, useEffect, useRef, useState} from "react";
import {useSelector} from "react-redux";
import {getSongLyric} from "../../services/music";
import {dealLyrics} from "../../utils";

const LyContainer = styled.ul.attrs(({theme}) => theme)`
  padding-bottom: 100vh;
  height: 100vh;
  overflow-y: scroll;
  text-align: center;
  color: rgba(255, 255, 255, 0.588);
  scroll-behavior: smooth;
`

const LyItem = styled.li.attrs({
    timing: props => props.timing
})`
  transition: all ease-in-out .288s;
  font-size: .4rem;
  margin: .4rem;
  cursor: pointer;

  &.active {
    color: #EFFFFD;
    font-weight: bolder;
    font-size: .5rem;
  }
`
export default memo(function LyricsComponents(props) {
    const {timing, onLineClick} = props
    const [lyricsData, setLyricsData] = useState([])
    const LyricsScrollRef = useRef([])
    const currentActiveIndex = useRef(0)
    const current = useSelector((state) => state.player.current)
    const handleGetCurrentLyrics = () => {
        getSongLyric({id: current.id}).then(res => {
            if (res.code !== 200) return
            setLyricsData(dealLyrics(res.lrc.lyric))
            currentActiveIndex.current = 0
        })
    }
    useEffect(() => {
        handleGetCurrentLyrics()
    }, [current])

    useEffect(() => {
        if (timing <= 0) return
        const childrenNodes = Array.from(LyricsScrollRef.current.children)
        const aimNodeLiIndex = childrenNodes.findIndex(item => {
            return timing <= item.getAttribute("data-timing")
        })
        if (aimNodeLiIndex !== currentActiveIndex.current && aimNodeLiIndex > -1) {
            currentActiveIndex.current = aimNodeLiIndex
            LyricsScrollRef.current.scrollTo(0, childrenNodes[aimNodeLiIndex].offsetTop-LyricsScrollRef.current.offsetHeight/1.5)
        }
    }, [timing])
    return <LyContainer ref={LyricsScrollRef}>
        {lyricsData.map((item, index) => {
            return <LyItem onClick={() => onLineClick && onLineClick(item.timing)}
                           className={`${index === currentActiveIndex.current - 1 ? 'active' : ""}`} key={item.timing}
                           data-timing={item.timing}>
                <span>{item.text}</span>
            </LyItem>
        })}
    </LyContainer>
})
